<template>
  <div>
    <!-- 树形数据转换 -->
  </div>
</template>
<script>
export default {
  created() {
    const list = [
      { id: 0, name: '广西', pid: '' },
      { id: 1, name: '广东', pid: '' },
      { id: 2, name: '广州', pid: 1 },
      { id: 3, name: '深圳', pid: 1 },
      { id: 4, name: '宝安', pid: 3 },
      { id: 5, name: '南山', pid: 3 },
      { id: 6, name: '石岩', pid: 4 },
      { id: 7, name: '创维', pid: 6 }
    ]
    // 需要转换成下面数据
    const result = [
      { id: 0, name: '广西', pid: '' },
      { id: 1, name: '广东', pid: '', children: [
        { id: 2, name: '广州', pid: 1 },
        { id: 3, name: '深圳', pid: 1, children: [
          { id: 5, name: '南山', pid: 3 },
          { id: 4, name: '宝安', pid: 3, children: [
            { id: 6, name: '石岩', pid: 4, children: [
              { id: 7, name: '创维', pid: 6 }
            ] }
          ] }
        ] }
      ] }
    ]
    console.log(this.changeData(list, ''))
  },
  methods: {
    // 树形数据转换
    changeData(arr, pid) {
      // 1: 只找出第一层数据
      // 2: 将pid写成形参
      // 3：将找出来的数据加入childre=[]
      // 4: 使用递归找出对应相的子集，子集的pid是父级的id
      return arr.filter(item => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>
<style>
</style>
